package com.cory.admin.sys.service;

import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cory.admin.sys.domain.entity.SysUser;
import com.cory.admin.sys.mapper.SysUserMapper;
import com.cory.boot.domain.enumdef.EState;
import com.cory.module.oplog.core.OpLogBaseService;
import com.cory.module.oplog.core.OpLogClient;
import com.cory.utils.lang.DateUtils;

/**
 * 登录用户信息表 服务实现类
 *
 * @author xc
 * @since 2019-02-23
 */
@Service
public class SysUserService extends OpLogBaseService<SysUserMapper, SysUser> {
    
    public List<SysUser> list(SysUser param) {
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.eq("tenant_id", param.getTenantId()).eq("user_type", param.getUserType()).ne("state", EState.DELETE.key);
        query.orderByDesc("id");
        if (StringUtils.isNotBlank(param.getUserName())) {
            query.like("user_name", "%" + param.getUserName() + "%");
        }
        if (StringUtils.isNotBlank(param.getLoginName())) {
            query.like("login_name", "%" + param.getLoginName() + "%");
        }
        if (StringUtils.isNotBlank(param.getMobile())) {
            query.like("mobile", "%" + param.getMobile() + "%");
        }
        if (StringUtils.isNotBlank(param.getPosition())) {
            query.like("position", "%" + param.getPosition() + "%");
        }
        if (StringUtils.isNotBlank(param.getDeptCode()) && !"0".equals(param.getDeptCode())) {
            query.like("dept_code", param.getDeptCode() + "%");
        }
        if (param.getState() != null) {
            query.eq("state", param.getState());
        }
        return super.list(query);
    }

    public SysUser getByLoginName(String loginName, Integer userType) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", loginName);

        if (userType != null && userType != -1) {
            wrapper.eq("user_type", userType);
        }
        return super.getOne(wrapper);
    }
    
    @Override
    public boolean delete(Integer id) {
        String date = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss");
        SysUser user = super.getById(id);
        user.setState(EState.DELETE.key);
        user.setLoginName(user.getLoginName() + "(" + date + ")");
        super.updateById(user);
        
        OpLogClient.log4Delete(user);
        return true;
    }

    public Integer getUserIdByUserName(Integer tenantId,String userName) {
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.eq("tenant_id", tenantId).ne("state", EState.DELETE.key);
        query.eq("user_name",userName);
        SysUser sysUser = super.getOne(query);
        return sysUser == null ? null : sysUser.getId();
    }
    
}
